# -*- coding:utf-8 -*-  

# Contact with the author by :
# itech001@126.com
# www.cnblogs.com/itech

import os
import threading
import subprocess
import time
from hashlib import md5
import logging


def run_command_with_output(cmd,stdinstr = ''):
    '''
    start one process to run cmd and make the stderr direct into stdout.
    '''
    p=subprocess.Popen(cmd, shell=True, universal_newlines=True, stdin=subprocess.PIPE, 
    stdout=subprocess.PIPE, stderr=subprocess.STDOUT
    )
    stdoutdata, stderrdata = p.communicate(stdinstr)
    return p.returncode, stdoutdata, stderrdata
  
def read_file(inPath):
    file = open(inPath, 'rb')
    fileStr = ''
    if file:
        fileStr = file.read()
        file.close()
    return fileStr

def read_file_lines(inPath):
    '''
        read the file by binary format.
    '''
    file = open(inPath, 'rb')
    if file:
        lines = file.readlines()
        file.close()
    return lines
    
def write_file(outPath,fileStr):
    '''
        write the file by binary format.
    '''
    file = open(outPath, 'wb')
    if file:
        file.write(fileStr)
        file.close()
        return True
    else:
        return False
        
def cal_MD5(s):
    '''
        caculate MD5 for the input string.
    '''
    m = md5()
    m.update(s)
    return m.hexdigest()
  
def hostname():
    '''
        get the nachine name for differenct platforms.
    '''
    sys = os.name  

    if sys == 'nt':  
            hostname = os.getenv('computername')  
            return hostname  

    elif sys == 'posix':  
            host = os.popen('echo $HOSTNAME')  
            try:  
                    hostname = host.read()  
                    return hostname  
            finally:  
                    host.close()
    else:  
            return 'Unkwon hostname' 
            
def temp_dir():
    '''
        get temp directory.
    '''
    curdir = os.getcwd()
    tempdir = os.path.join(curdir,'temp')
    if not os.path.exists(tempdir): 
        os.makedirs(tempdir)
    return tempdir

class PyRRLogger():
    '''
        custom logger, you can control log to console or file or both of them.
    '''
    loginstance = None

    @staticmethod
    def instance():
        if not PyRRLogger.loginstance:
            PyRRLogger.loginstance = PyRRLogger()
        return PyRRLogger.loginstance

    def __init__(self, loglevel=logging.DEBUG, logtoconsole=True, logtofile=""):
        self.logger = logging.getLogger("PyRR")
        self.logger.setLevel(loglevel)

        # create formatter and add it to the handlers
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")    

        # create file handler which logs even debug messages
        if logtofile:
            fh = logging.FileHandler(logtofile)
            fh.setFormatter(formatter)
            self.logger.addHandler(fh)

        # create console handler with a higher log level
        if logtoconsole:
            ch = logging.StreamHandler()
            ch.setFormatter(formatter)
            self.logger.addHandler(ch)
            
    def debug(self, s):
        self.logger.debug(s)
        
    def error(self, s):
        self.logger.error(s)

def is_cmd_or_scriptfn(s):
    if(s.startswith("-c:")):
        return 'cmd', s[s.index(':') + 1 :]
    elif(s.startswith("-sf:")):
         return 'scriptfn', s[s.index(':') + 1:]
    else:
         return '', ''
         
def get_excutable_by_ext(ext):
    ext_and_excutables = {}
    ext_and_excutables['.bat'] = ''
    ext_and_excutables['.com'] = ''
    ext_and_excutables['.py'] = 'python'
    ext_and_excutables['.pl'] = 'perl'
    ext_and_excutables['.sh'] = 'sh'
    return ext_and_excutables.get(ext)
